import { createRouter, createWebHashHistory } from 'vue-router'
import { isUrl } from '@/utils/is'
import { omit, cloneDeep } from 'lodash'
// 自动导入 views 下所有 vue/tsx 文件
const modules = import.meta.glob('../views/**/*.{vue,tsx}')

/* Layout 组件 */
export const Layout = () => import('@/layout/Layout.vue')

/* 占位父级组件（嵌套路由中用） */
export const getParentLayout = () => () => Promise.resolve({ name: 'ParentLayout' })

/**
 * 基于后端返回的路由表，动态生成 Vue Router 路由对象数组
 * @param routes 后端传递的路由结构
 */
export const generateRoutesByServer = (routes = []) => {
  const res = []

  for (const route of routes) {
    if (route.meta?.type === 'B') continue // 过滤按钮权限项

    const data = {
      path: route.path,
      name: route.name,
      url:route?.url,
      redirect: route.redirect,
      meta: route.meta || {},
      children: []
    }

    if (route.component) {
      // 先清理 component 字段前后的斜杠，防止重复
      let rawPath = route.component.replace(/^\/+|\/+$/g, '');

      // 拼接为 modules 里的 key，modules key 都是 '../views/xxx.vue'
      // 如果后端给的是 'views/system/user/index'，你需要加上 '../' 和 '.vue'
      rawPath = `../${rawPath}.vue`;

      const comModule = modules[rawPath];

      if (!comModule && !route.component.includes('#')) {
        console.error(`未找到组件：${rawPath}`);
      } else {
        data.component =
          route.component === '#'
            ? Layout
            : route.component.includes('##')
              ? getParentLayout()
              : comModule;
      }
    }


    if (Array.isArray(route.children) && route.children.length) {
      data.children = generateRoutesByServer(route.children)
    }

    res.push(data)
  }

  return res
}

/**
 * 扁平化后端路由结构，仅保留菜单项
 * @param routers 后端传入的原始路由数据
 */
export const removeButtonMenu = (routers = []) => {
  return routers
    .filter(item => item.meta?.type !== 'B' && !item.meta?.hidden)
    .map(item => ({
      ...item,
      children: item.children ? removeButtonMenu(item.children) : []
    }))
}

/**
 * 降级多层级嵌套路由为两级
 * @param routes - 原始路由表
 * @returns 降级后的路由表
 */
export const flatMultiLevelRoutes = (routes) => {
  const modules = cloneDeep(routes)

  for (let index = 0; index < modules.length; index++) {
    const route = modules[index]
    if (!isMultipleRoute(route)) {
      continue
    }
    promoteRouteLevel(route)
  }

  return modules
}
/**
 * 去除 matched 之后的 route 对象（防止结构过深）
 */
export const getRawRoute = (route) => {
  if (!route) return route
  const { matched, ...opt } = route
  return {
    ...opt,
    matched: matched
      ? matched.map((item) => ({
        meta: item.meta,
        name: item.name,
        path: item.path
      }))
      : undefined
  }
}

/**
 * 是否存在多层级 children
 */
const isMultipleRoute = (route) => {
  if (!route || !route.children || !route.children.length) return false

  for (const child of route.children) {
    if (child.children && child.children.length) return true
  }

  return false
}

/**
 * 拼接路径并处理双斜杠
 */
export const pathResolve = (parentPath, path) => {
  if (isUrl(path)) return path
  const childPath = path.startsWith('/') || !path ? path : `/${path}`
  return `${parentPath}${childPath}`.replace(/\/\//g, '/').trim()
}
